package com.tj.exceldemo.excel_demo.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.CollectionUtils;
import com.tj.exceldemo.excel_demo.handler.ProgressHandler;
import com.tj.exceldemo.excel_demo.vo.ImportTestInfo;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.core.internal.util.CollectionUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class FileImportService {

    @Resource
    private ProgressHandler progressHandler;

    @Async
    public void importFileAsync(MultipartFile file) {
        // 执行文件导入的逻辑
        // 假设导入过程中可以获取到导入的总行数
        List<ImportTestInfo> totalList = null;
        int totalRows = 0;
        try {
            totalList = getImportRows(file);
        } catch (IOException e) {
            log.error("读取文件出错：" + e.getMessage());
        }
        if (CollectionUtils.isEmpty(totalList)) {
            log.info("读取文件为空,导入结束");
            return;
        }
        totalRows = totalList.size();
        double progress = 0;

        for (int i = 0; i < totalRows; i++) {
            try {
                // 处理每一行数据的导入逻辑
                Thread.sleep(500);
                System.out.println(totalList.get(i).toString());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 更新进度
            progress = (double) (i + 1) * 100 / totalRows;
            System.out.println(progress);
            progressHandler.updateProgress(progress);
        }

        // 导入完成后更新进度为100%
        progressHandler.updateProgress(100);

    }

    List<ImportTestInfo> getImportRows(MultipartFile file) throws IOException {

        List<ImportTestInfo> list = EasyExcel.read(file.getInputStream()).head(ImportTestInfo.class)
                .sheet().doReadSync();
        return list;

    }
}

